package huoye.shops.huoye.operation.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.method.ScrollingMovementMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.codeideology.android.utils.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.huoye.operation.adapter.SharePondAdapter;
import huoye.shops.huoye.operation.model.EventInfo;
import huoye.shops.huoye.operation.model.EventOddPrizeList;
import huoye.shops.huoye.operation.model.GuessAll;
import huoye.shops.huoye.operation.model.ManageEventData;
import huoye.shops.huoye.operation.model.Prize;
import huoye.shops.huoye.operation.model.SharePondData;
import huoye.shops.huoye.operation.model.SharePool;
import huoye.shops.huoye.operation.model.ToUrl;
import huoye.shops.huoye.operation.presenter.EventQmcclPresenter;
import huoye.shops.huoye.operation.presenter.SharePondPresenter;
import huoye.shops.huoye.operation.view.IEventQmcclView;
import huoye.shops.huoye.operation.view.ISharePondView;
import huoye.shops.huoye.operation.widget.EventCodeDialog;
import huoye.shops.huoye.operation.widget.SelectPrizeNumDialog;
import huoye.shops.utils.StockUtils;
import huoye.shops.utils.ViewUtils;
import huoye.shops.widget.CommonHintDialog;
import huoye.shops.widget.RoundImageView;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_INTENT_PRIZE_TYPE_URL;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_SELECT_IMAGE;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_SELECT_PRIZE_ID;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_SELECT_STOCK;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_TYPE;
import static huoye.shops.utils.StockUtils.setTimeStyle;

public class EventQmcclActivity extends BaseActivity implements IEventQmcclView {

    @BindView(R.id.event_qmccl_tv_rule)
    TextView tvRule;
    @BindView(R.id.event_qmccl_tv_join_user)
    TextView tvJoinUser;

    @BindView(R.id.event_qmccl_tv_mine_put_limit)
    TextView tvMinePutLimit;

    @BindView(R.id.event_qmccl_tv_join_set)
    TextView tvJoinSet;


    @BindView(R.id.event_qmccl_ll_mine_put_limit)
    LinearLayout llMinePutLimit;

    @BindView(R.id.event_qmccl_ll_naming)
    LinearLayout llNaming;

    @BindView(R.id.event_qmccl_ll_event_share)
    LinearLayout llEventShare;
    @BindView(R.id.event_qmccl_tv_event_share)
    TextView tvEventShare;


    @BindView(R.id.item_qmccl_share_set_rv)
    RelativeLayout rvQmccl;
    @BindView(R.id.item_qmccl_share_set_tv_winning)
    TextView tvWinning;
    @BindView(R.id.item_qmccl_share_set_tv_prize_number)
    TextView tvPrizeNumber;
    @BindView(R.id.item_qmccl_share_set_iv_add_image)
    ImageView ivAddImage;
    private EventOddPrizeList eventOddPrizeQmccl = new EventOddPrizeList();;
    private EventInfo eventInfo;


    @BindView(R.id.event_qmccl_btn_is_prize)
    Button btnIsPrize;

    @OnClick(R.id.event_qmccl_btn_is_prize)
    void onIsPrizeClick() {
      startActivity(CurUserLotteryInfosActivity.class,eventInfo);
    }


    @OnClick(R.id.item_qmccl_share_set_iv_add_image)
    void onAddImageQmcclClick() {
        Intent intent = new Intent(getApplicationContext(), ManagePrizeActivity.class);
        intent.putExtra(EXTRAS_KEY_PRIZE_TYPE, "1");
        startActivityForResult(intent, EXTRAS_INTENT_PRIZE_TYPE_URL);
    }


    @BindView(R.id.event_qmccl_tv_naming_shop)
    TextView tvNamingShop;
    @BindView(R.id.event_qmccl_tv_naming_shop_hint)
    TextView tvNamingShopHint;
    @BindView(R.id.event_qmccl_rv_naming_head)
    RoundImageView rvNamingHea;

    @BindView(R.id.event_qmccl_tv_residue_time_day)
    TextView tvTimeOne;
    @BindView(R.id.event_qmccl_tv_residue_time_hout)
    TextView tvTimeTwo;
    @BindView(R.id.event_qmccl_tv_residue_time_minute)
    TextView tvTimeThree;
    @BindView(R.id.event_qmccl_btn_join_affirm)
    Button btnJoinAffirm;
    @BindView(R.id.event_qmccl_btn_queus_shop)
    Button btnQueusShop;


    @OnClick(R.id.event_qmccl_btn_queus_shop)
    void onQueusShopClick() {
        startActivity(QueueShopActivity.class,mEventData);
    }




    @Override                           //requestCode请求标记,resultCode是返回标记
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == EXTRAS_INTENT_PRIZE_TYPE_URL) {
           String number = data.getStringExtra(EXTRAS_KEY_PRIZE_SELECT_STOCK);
            String image = data.getStringExtra(EXTRAS_KEY_PRIZE_SELECT_IMAGE);
            String prizeId = data.getStringExtra(EXTRAS_KEY_PRIZE_SELECT_PRIZE_ID);

               // tvPrizeNumber.setText(number);
                //目前写死  参加全民猜猜乐只用一个奖品
          /*       tvPrizeNumber.setText("1/1");
                eventOddPrizeQmccl.setPrizeNum("1");
                Glide.with(this)
                        .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + image)
                        .dontAnimate()
                        .placeholder(R.mipmap.ic_wait_logo)
                        .error(R.mipmap.ic_error)
                        .into(ivAddImage);
             //   eventOddPrizeQmccl.setPrizeNum(number);
                eventOddPrizeQmccl.setPrizeImg(image);
                eventOddPrizeQmccl.setPrizeId(prizeId);
*/

          showSelectPrizeNum(number,image,prizeId);
        }
    }


    private void showSelectPrizeNum(String number, String image, String prizeId){
        int  mNum = Integer.valueOf(number);
        SelectPrizeNumDialog selectPrizeNumDialog = new SelectPrizeNumDialog(this);
        selectPrizeNumDialog.setSelectPrizeNumListener(new SelectPrizeNumDialog.OnSelectPrizeNumListener() {

            @Override
            public void onRightClick(int prizeNum) {
                tvPrizeNumber.setText(prizeNum+"/"+prizeNum);
                Glide.with(getApplicationContext())
                        .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + image)
                        .dontAnimate()
                        .placeholder(R.mipmap.ic_wait_logo)
                        .error(R.mipmap.ic_error)
                        .into(ivAddImage);
                eventOddPrizeQmccl.setPrizeNum(prizeNum+"");
                eventOddPrizeQmccl.setPrizeImg(image);
                eventOddPrizeQmccl.setPrizeId(prizeId);

            }
        });
        selectPrizeNumDialog.show();
        selectPrizeNumDialog.setNum(mNum);
    }



    private EventQmcclPresenter mEventQmcclPresenter;


    @OnClick(R.id.event_qmccl_btn_join_affirm)
    void onJoinAffirmClick() {
        addQmcclEvent();
    }

    private void addQmcclEvent() {
        List<EventOddPrizeList> listQmccl = new ArrayList<>();
        if(!StringUtils.isNotEmpty(eventOddPrizeQmccl.getPrizeId())){
            makeToast("参与活动的奖品不能为空");
            return;
        }
        if(!StringUtils.isNotEmpty(eventOddPrizeQmccl.getPrizeNum())||eventOddPrizeQmccl.getPrizeNum().equals("0")){
            makeToast("奖品数量不能为空");
            return;
        }

        listQmccl.add(eventOddPrizeQmccl);
        mSharePondData.getSharePool().setEventOddPrizeList(listQmccl);
        mEventQmcclPresenter.joinEvent(mSharePondData);

    }


    private Date eDate;
    private ManageEventData mEventData;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_event_qmccl;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        mEventData = getIntentData();
        mEventQmcclPresenter = new EventQmcclPresenter();
        mEventQmcclPresenter.addTaskListener(this);
        mEventQmcclPresenter.onStart();
        mEventQmcclPresenter.getEventDetail(mEventData.getEventId());


    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(mRunnable);
    }

    private Handler handler = new Handler();
    private Runnable mRunnable;

    private void timer() {
        mRunnable = new Runnable() {
            @Override
            public void run() {
                if (eDate != null) {
                    showDistanceTime(eDate);
                }
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(mRunnable, 1000);
    }


    private void showDistanceTime(Date endDate) {
        Date now = new Date();

        long hour = ViewUtils.getDistanceTimeHourDay(now, endDate);
        long min = ViewUtils.getDistanceTimemin(now, endDate);
        long second = ViewUtils.getDistanceTimeSecond(now, endDate);

        if (hour == 0 && min == 0 && second == 0) {
            makeToast("活动结束");
            hideRightBtn();
            btnJoinAffirm.setVisibility(GONE);
            handler.removeCallbacks(mRunnable);
            tvTimeOne.setText("00");
            tvTimeTwo.setText("00");
            tvTimeThree.setText("00");
            eDate = null;

        }

        if (hour == 0 && min == 0) {
            tvTimeOne.setText("00");
            tvTimeTwo.setText("00");
            tvTimeThree.setText(setTimeStyle(second));
        } else if (hour == 0) {
            tvTimeOne.setText("00");
            tvTimeTwo.setText(setTimeStyle(min));
            tvTimeThree.setText(setTimeStyle(second));
        } else {
            tvTimeOne.setText(setTimeStyle(hour));
            tvTimeTwo.setText(setTimeStyle(min));
            tvTimeThree.setText(setTimeStyle(second));
        }


    }


    private SharePondData mSharePondData;



    @Override
    public void setEventData(SharePondData sharePondData) {
        this.mSharePondData = sharePondData;
        eventInfo = sharePondData.getEventInfo();

        showQMCCL();
        String endTime = eventInfo.getEndTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            eDate = sdf.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //活动状态 0-未开始 1-已开始 2-已结束
        if (sharePondData.getEventInfo().getiState() == 2) {
            tvTimeOne.setText("00");
            tvTimeTwo.setText("00");
            tvTimeThree.setText("00");
            btnJoinAffirm.setVisibility(View.INVISIBLE);
            btnJoinAffirm.setEnabled(false);
            btnJoinAffirm.setClickable(false);
            hideRightBtn();
        } else {
            timer();
        }


        String mineMoeny = StockUtils.moenyStyleNoZero(eventInfo.getCurrentTotalMoney());
        tvMinePutLimit.setText(mineMoeny+ "");

    }








    private  Prize mPrize;
    //显示全民猜猜乐的数据
    private void showQMCCL() {
        GuessAll guessAll = mSharePondData.getGuessAll();

        if(guessAll.isPrize()) {
            btnIsPrize.setVisibility(VISIBLE);
        }

        if (eventInfo.getRemarks() == null) {
            eventInfo.setRemarks("");
        }
        tvRule.setText(eventInfo.getRemarks());
        tvRule.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvRule.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //通知父控件不要干扰
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    //通知父控件不要干扰
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }
                return false;
            }
        });
        tvJoinUser.setText(eventInfo.getTotalNum());
        setTitle(mSharePondData.getEventInfo().getEtClassName());



        //是否当前商家冠名
        if (guessAll.isCurShopNaming()) {
            mPrize = guessAll.getPrize();
            showQmcclPrize();
            llMinePutLimit.setVisibility(VISIBLE);
        }else {
            llMinePutLimit.setVisibility(View.INVISIBLE);
        }


        if ( guessAll.isNaming()) {
            tvNamingShopHint.setText(guessAll.getShopName());
            Glide.with(this)
                    .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + guessAll.getShopLogo())
                    .dontAnimate()
                    .placeholder(R.mipmap.ic_wait_logo)
                    .error(R.mipmap.ic_error)
                    .into(rvNamingHea);
        }

        if(guessAll.isJoin()){
            btnJoinAffirm.setVisibility(View.INVISIBLE);
            ivAddImage.setClickable(false);
            ivAddImage.setEnabled(false);
        }else{
            if(guessAll.isNaming()){
                btnJoinAffirm.setVisibility(View.INVISIBLE);
            }else {
                btnJoinAffirm.setVisibility(VISIBLE);
            }
        }


       //活动状态 0-未开始 1-已开始 2-已结束`
        if ((mSharePondData.getEventInfo().getiState() != 2 && !guessAll.isNaming() ) || guessAll.isCurShopNaming()) {
            rvQmccl.setVisibility(VISIBLE);
            tvJoinSet.setVisibility(VISIBLE);
            llMinePutLimit.setVisibility(VISIBLE);
            mPrize = guessAll.getPrize();
            showQmcclPrize();
        }else {
            llMinePutLimit.setVisibility(GONE);
        }


        //1-共享奖池 2-地动三摇 3-地动三摇自动版
        if(eventInfo.getEtClassType() == 3){
            btnJoinAffirm.setText("确认参与排队");
            btnQueusShop.setVisibility(VISIBLE);
            btnJoinAffirm.setVisibility(VISIBLE);
            rvQmccl.setVisibility(VISIBLE);
            ivAddImage.setClickable(true);
            ivAddImage.setEnabled(true);
            llEventShare.setVisibility(VISIBLE);
            tvEventShare.setText(eventInfo.getShareNum()+"");
        }else {
            btnJoinAffirm.setText("确认参加");
        }



    }


    private void showQmcclPrize(){
        tvPrizeNumber.setText(mPrize.getPrizeNum());
        if(StringUtils.isNotEmpty(mPrize.getPrizeImg())){
            Glide.with(this)
                    .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + mPrize.getPrizeImg())
                    .dontAnimate()
                    .placeholder(R.mipmap.ic_wait_logo)
                    .error(R.mipmap.ic_error)
                    .into(ivAddImage);
        }
    }





}
